package com.weactivity.controller;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.weactivity.dto.Result;
import com.weactivity.dto.registerFormDTO;
import com.weactivity.entity.User;
import com.weactivity.service.UserService;
import com.weactivity.utils.JwtUtil;
import com.weactivity.utils.Md5Util;
import com.weactivity.utils.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session){
        return userService.sendCode(phone,session,RedisConstant.LOGIN_CODE_KEY,RedisConstant.LOGIN_CODE_TTL,TimeUnit.MINUTES);
    }

    @PostMapping("/registerCode")
    public Result sendRegisterCode(@RequestParam("phone") String phone, HttpSession session){
        System.out.println(phone);
        return userService.sendCode(phone,session, RedisConstant.REGISTER_CODE_KEY,RedisConstant.REGISTER_CODE_TTL, TimeUnit.MINUTES);
    }

    @PostMapping("/retrieveCode")
    public Result sendRetrieveCode(@RequestParam("phone") String phone, HttpSession session){
        System.out.println(phone);
        return userService.sendCode(phone,session, RedisConstant.RETRIEVE_CODE_KEY,RedisConstant.RETRIEVE_CODE_TTL, TimeUnit.MINUTES);
    }




    @PostMapping("/register")
    public Result register(@RequestBody registerFormDTO registerForm, HttpSession session){
        //首先根据用户手机号判断用户是否已经注册
        //不在才可以注册
        //前端检测phone不为空
        //但还是需要检测是否为空，防止某些请求绕过前端
        String phone = registerForm.getPhone();
        if(null == phone){
            return Result.fail("phone不能为空");
        }

        User u = userService.findByPhone(phone);

        //如果从数据库中找到了用户，说明已注册
        if(null != u){
            return Result.fail("手机号已注册");
        }

        //没找到用户，说明没有注册，进行注册的业务
        return userService.register(registerForm , session);
    }

    //用户登录
    @PostMapping("/login")
    public Result loginByName(@RequestParam("userName") @Pattern(regexp = "^\\S{5,16}$") String userName, @RequestParam("password") @Pattern(regexp = "^//S{5,16}$") String password,HttpSession session){

        System.out.println("进入userController");
        //输入username password
        //查找用户存在
        User user = userService.findByUserName(userName);
        if (null == user){
            //不存在返回错误
            return Result.fail("用户不存在");
        }
        //存在后需要判断用户密码是否匹配
        if(!Md5Util.getMD5String(password).equals(user.getPassword())){
            return Result.fail("密码错误");
        }

        Map<String,Object> claims =new HashMap<>();
        claims.put("id",user.getId());
        claims.put("userName",user.getNickName());
        claims.put("icon",user.getIcon());

        String token = JwtUtil.genToken(claims);
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.set(token,token,1, TimeUnit.HOURS);
        return Result.ok(token);

    }

    @PostMapping("/retrieve")
    public Result retrievePassword(@RequestParam("phone") @Pattern(regexp = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$") String phone ,
                                   @RequestParam("code") String code,
                                   @RequestParam("password") String password){

        //找回密码
        //用户点击找回密码按钮，发送请求
        //用户输入手机号

        //检测手机号是否注册
        System.out.println(phone);
        User u = userService.findByPhone(phone);

        //如果从数据库中找到了用户，说明已注册
        if(null == u){
            return Result.fail("手机号未注册");
        }

        // 点击发送验证码
        //通过调用sendRetrieveCode接口发送
        // 匹配
        String codeToCompare = stringRedisTemplate.opsForValue().get(RedisConstant.RETRIEVE_CODE_KEY + phone);
        if(!codeToCompare.equals(code)){
            return Result.fail("验证码不匹配");
        }

        String md5String = Md5Util.getMD5String(password);

        //输入新密码，update password
        int isUpdated = userService.updatePassword(phone,md5String);
        //返回修改成功消息
        if(1 != isUpdated){
            return Result.fail("修改失败");
        }
        //跳转页面，未实现
        return Result.ok();

    }

    /**
     * 在首页返回用户的信息
     * 包括用户名，用户icon
     *
     * @return
     */
//    @GetMapping("/userinfo")
//    public Result UserInfo(){
//
//        Map<String,Object> map = userService.findUserInfo();
//
//
//
//    }





}
